package com.winning.pmph.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.jcommander.internal.Maps;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import com.winning.pmph.entity.IncreaseQrCode;
import com.winning.pmph.entity.IncreaseResource;
import com.winning.pmph.entity.KnowledgeLib;
import com.winning.pmph.enumeration.KnowledgeSystem;
import com.winning.pmph.mapper.IncreaseBookMapper;
import com.winning.pmph.mapper.IncreaseQrCodeMapper;
import com.winning.pmph.mapper.IncreaseResourceMapper;
import com.winning.pmph.schedule.QuartzManager;
import com.winning.pmph.utils.ApplicationContextUtil;
import com.winning.pmph.utils.ExcelUtil;
import com.winning.pmph.utils.FfmpegUtil;
import com.winning.pmph.utils.HttpApi;
import com.winning.pmph.utils.PMPHAppUtil;
import com.winning.pmph.utils.PptToImg;
import com.winning.pmph.utils.RocketMQProducerUtil;
import com.winning.pmph.vo.CategorySelectVo;
import com.winning.pmph.vo.IncreaseResourceVo;
import com.winning.pmph.vo.ResourceTreeVo;
import com.winning.pmph.vo.UploadFileVo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ZipUtil;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lbm
 * @since 2021-12-30
 */
@Service
public class IncreaseResourceService extends ServiceImpl<IncreaseResourceMapper, IncreaseResource> {
	@Autowired
	IncreaseBookMapper increaseBookMapper;
	@Autowired
	IncreaseQrCodeMapper increaseQrCodeMapper;
	@Autowired
	QuartzManager quartzManager;
	@Autowired
	KnowledgeSyncStatusService knowledgeSyncStatusService;

	public void importResource(MultipartFile multipartFile, String bookId, String categoryId) throws IOException {
		if (StringUtils.isBlank(bookId)) {
			return;
		}

		// 解析xls文件
		String oriFileName = multipartFile.getOriginalFilename();
		int position = oriFileName.lastIndexOf(".");
		String extName = oriFileName.substring(position);
		Workbook workBook = null;
		if (".xlsx".equals(extName)) {
			workBook = new XSSFWorkbook(multipartFile.getInputStream());
		} else if (".xls".equals(extName)) {
			workBook = new XSSFWorkbook(multipartFile.getInputStream());
		}
		excelHandler(workBook, bookId, categoryId);
	}
	
	public void importGroupResource(MultipartFile multipartFile, String resourceId, String categoryId) throws IOException {
		if (StringUtils.isBlank(resourceId)) {
			return;
		}
		// 解析xls文件
		String oriFileName = multipartFile.getOriginalFilename();
		int position = oriFileName.lastIndexOf(".");
		String extName = oriFileName.substring(position);
		Workbook workBook = null;
		if (".xlsx".equals(extName)) {
			workBook = new XSSFWorkbook(multipartFile.getInputStream());
		} else if (".xls".equals(extName)) {
			workBook = new HSSFWorkbook(multipartFile.getInputStream());
		}
		excelGroupResourceHandler(workBook, resourceId, categoryId);
	}

	public void excelHandler(Workbook workBook, String bookId, String categoryId) {
		if (StringUtils.isBlank(categoryId)) {
			categoryId = bookId;
		}
		int startSortNum = getStartNum(categoryId);
		try {
			Sheet sheet = workBook.getSheetAt(0);
			Row rowTitle = sheet.getRow(0);
			int cellNum = rowTitle.getLastCellNum();
			Map<String,Integer> titleMap = new HashMap<>();
			for (int i = 0; i < cellNum; i++) {
				String cellValue = rowTitle.getCell(i).getStringCellValue();
				if(StringUtils.isBlank(cellValue)) {
					continue;
				}
				if("二维码名称".equals(cellValue)) {
					titleMap.put("qrCodeName", i);
				}else if("资源名称（显示名称）".equals(cellValue)) {
					titleMap.put("resourceName", i);
				}else if("文件名称".equals(cellValue)) {
					titleMap.put("fileName", i);
				}else if("文件名后缀".equals(cellValue)) {
					titleMap.put("suffix", i);
				}
			}
			
			int rowNum = sheet.getLastRowNum();
			for (int i = 1; i <= rowNum; i++) {
				Row row = sheet.getRow(i);
				
				String qrCodeName = ExcelUtil.getCellStr(row.getCell(titleMap.get("qrCodeName")));
				String resourceName = ExcelUtil.getCellStr(row.getCell(titleMap.get("resourceName")));
				String fileName = ExcelUtil.getCellStr(row.getCell(titleMap.get("fileName")));
				String suffix = ExcelUtil.getCellStr(row.getCell(titleMap.get("suffix")));
				if (StringUtils.isBlank(resourceName)) {
					continue;
				}

				Date nowTime = new Date();
				IncreaseResource resource = new IncreaseResource();
				String id = IdWorker.getIdStr();
				resource.setId(id);
				resource.setName(resourceName);
				resource.setBookId(bookId);

				resource.setFileName(fileName);
				resource.setResourceSuffix(suffix);
				resource.setResourceType(FfmpegUtil.getResourceType(suffix));
				resource.setCreateTime(nowTime);
				resource.setUpdateTime(nowTime);
				resource.setCreateBy(PMPHAppUtil.getCurrentUserEnName());
				resource.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
				resource.setCateId(categoryId);
				resource.setPid(categoryId);
				resource.setSortNum(startSortNum);
				resource.setIsSub(0);
				this.baseMapper.insert(resource);
				if (StringUtils.isNotBlank(qrCodeName)) {
					IncreaseQrCode qrCode = new IncreaseQrCode();
					qrCode.setName(qrCodeName);
					qrCode.setSourceId(id);
					qrCode.setSourceType(2);
					qrCode.setCreateTime(DateUtil.now());
					qrCode.setUpdateTime(DateUtil.now());
					qrCode.setCreateBy(PMPHAppUtil.getCurrentUserEnName());
					qrCode.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
					increaseQrCodeMapper.insert(qrCode);
				}
				startSortNum++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				workBook.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void excelGroupResourceHandler(Workbook workBook, String resourceId, String categoryId) {
		if (StringUtils.isBlank(categoryId)) {
			categoryId = resourceId;
		}
		int startSortNum = getGroupResourceStartNum(resourceId);
		try {
			Sheet sheet = workBook.getSheetAt(0);
			//解析所有列的标头
			Row rowTitle = sheet.getRow(0);
			int cellNum = rowTitle.getLastCellNum();
			Map<String,Integer> titleMap = new HashMap<>();
			for (int i = 0; i < cellNum; i++) {
				String cellValue = rowTitle.getCell(i).getStringCellValue();
				if(StringUtils.isBlank(cellValue)) {
					continue;
				}
				if("资源名称".equals(cellValue)) {
					titleMap.put("resourceName", i);
				}else if("图片注释".equals(cellValue)) {
					titleMap.put("imgNote", i);
				}else if("音频文件".equals(cellValue)) {
					titleMap.put("audioName", i);
				}else if("图片名称".equals(cellValue)) {
					titleMap.put("imgName", i);
				}
			}
			
			int rowNum = sheet.getLastRowNum();
			for (int i = 1; i <= rowNum; i++) {
				Row row = sheet.getRow(i);
				String resourceName = ExcelUtil.getCellStr(row.getCell(titleMap.get("resourceName")));
				String imgNote = ExcelUtil.getCellStr(row.getCell(titleMap.get("imgNote")));
				String audioName = ExcelUtil.getCellStr(row.getCell(titleMap.get("audioName")));
				String imgName = ExcelUtil.getCellStr(row.getCell(titleMap.get("imgName")));
				if (StringUtils.isBlank(resourceName)) {
					continue;
				}

				IncreaseResource resource = new IncreaseResource();
				String id = IdWorker.getIdStr();
				resource.setId(id);
				resource.setName(resourceName);
				resource.setFileName(imgName);
				resource.setImgNote(imgNote);
				resource.setAudioName(audioName);
				resource.setCateId(categoryId);
				resource.setResourceId(resourceId);
				resource.setResourceType(4);
				resource.setIsSub(1);
				resource.setSortNum(startSortNum);
				resource.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
				resource.setUpdateTime(new Date());
				resource.setCreateBy(PMPHAppUtil.getCurrentUserEnName());
				resource.setCreateTime(new Date());
				this.baseMapper.insert(resource);
				startSortNum++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				workBook.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void addResource(IncreaseResourceVo increaseResourceVo) throws Exception {
		IncreaseResource resource = new IncreaseResource();
		BeanUtils.copyProperties(increaseResourceVo, resource);
		String path = increaseResourceVo.getPath();

		if (StringUtils.isNotBlank(path)) {
			String fileSuffix = path.substring(path.lastIndexOf(".") + 1);
			resource.setResourceType(FfmpegUtil.getResourceType(fileSuffix));
			resource.setResourceSuffix(fileSuffix);
			String abPath = ApplicationContextUtil.BASE_DOWN_FORDER + path;
			resourceFileHandler(abPath, resource, null);
		}
		String cateId = increaseResourceVo.getCateId();
		if (StringUtils.isBlank(cateId)) {
			cateId = increaseResourceVo.getBookId();
		}
		int startSortNum = getStartNum(cateId);
		String resourceId = IdWorker.getIdStr();
		resource.setId(resourceId);
		resource.setCateId(cateId);
		resource.setPid(cateId);
		resource.setSortNum(startSortNum);
		resource.setIsSub(0);

		resource.setCreateBy(PMPHAppUtil.getCurrentUserEnName());
		resource.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
		resource.setUpdateTime(new Date());
		resource.setCreateTime(new Date());
		this.baseMapper.insert(resource);

		// 处理二维码相关
		saveQrCode(resourceId, increaseResourceVo.getQrCodeName());
	}

	public void editResource(IncreaseResourceVo increaseResourceVo) throws Exception {
		String resourceId = increaseResourceVo.getId();
		IncreaseResource resource = new IncreaseResource();
		BeanUtils.copyProperties(increaseResourceVo, resource);
		String path = increaseResourceVo.getPath();
		IncreaseResource increaseResource = this.getById(resourceId);

		if (StringUtils.isNotBlank(path) && !path.equals(increaseResource.getPath())) {
			String fileSuffix = path.substring(path.lastIndexOf(".") + 1);
			resource.setResourceType(FfmpegUtil.getResourceType(fileSuffix));
			String abPath = ApplicationContextUtil.BASE_DOWN_FORDER + path;
			resourceFileHandler(abPath, resource, increaseResource);
		}

		resource.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
		resource.setUpdateTime(new Date());
		this.baseMapper.updateById(resource);

		// 处理二维码相关
		saveQrCode(resourceId, increaseResourceVo.getQrCodeName());
	}

	public void saveQrCode(String resourceId, String qrCodeName) {
		// 处理二维码相关
		QueryWrapper<IncreaseQrCode> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("source_id", resourceId);
		List<IncreaseQrCode> list = increaseQrCodeMapper.selectList(queryWrapper);
		IncreaseQrCode qrCode = new IncreaseQrCode();
		if (list != null && list.size() > 0) {
			qrCode = list.get(0);
			if (!qrCodeName.equals(qrCode.getName())) {
				qrCode.setName(qrCodeName);
				qrCode.setUpdateTime(DateUtil.now());
				qrCode.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
				increaseQrCodeMapper.updateById(qrCode);
			}
		} else {
			qrCode.setId(IdWorker.getIdStr());
			qrCode.setName(qrCodeName);
			qrCode.setSourceId(resourceId);
			qrCode.setSourceType(2);
			qrCode.setCreateTime(DateUtil.now());
			qrCode.setUpdateTime(DateUtil.now());
			qrCode.setCreateBy(PMPHAppUtil.getCurrentUserEnName());
			qrCode.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
			increaseQrCodeMapper.insert(qrCode);
		}
	}

	public IncreaseQrCode getQrCode(String resourceId) {
		QueryWrapper<IncreaseQrCode> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("source_id", resourceId);
		List<IncreaseQrCode> list = increaseQrCodeMapper.selectList(queryWrapper);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	public void createResourceGroup(IncreaseResourceVo increaseResourceVo) {
		String cateId = increaseResourceVo.getCateId();
		if (StringUtils.isBlank(cateId)) {
			cateId = increaseResourceVo.getBookId();
		}
		int startSortNum = getStartNum(cateId);
		IncreaseResource resource = new IncreaseResource();
		String id = IdWorker.getId() + "";
		resource.setId(id);
		resource.setName(increaseResourceVo.getName());
		resource.setBookId(increaseResourceVo.getBookId());
		resource.setCateId(cateId);
		resource.setResourceType(4);
		resource.setResourceId(id);
		resource.setSortNum(startSortNum);
		resource.setCreateBy(PMPHAppUtil.getCurrentUserEnName());
		resource.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
		resource.setUpdateTime(new Date());
		resource.setCreateTime(new Date());
		resource.setIsSub(0);
		this.baseMapper.insert(resource);

		// 添加二维码
		String qrCodeName = increaseResourceVo.getQrCodeName();
		saveQrCode(id, qrCodeName);
	}

	/**
	 * 组下的资源的cateId，代表的是资源组目录的ID，与图书中的目录ID无关,通过issub判断
	 * 
	 * @param increaseResourceVo
	 */
	public void addGroupResource(IncreaseResourceVo increaseResourceVo) {
		IncreaseResource resource = new IncreaseResource();
		resource.setName(increaseResourceVo.getName());
		resource.setPath(increaseResourceVo.getPath());
		resource.setImgNote(increaseResourceVo.getImgNote());
		resource.setFileName(increaseResourceVo.getFileName());
		resource.setAudioPath(increaseResourceVo.getAudioPath());
		resource.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
		resource.setUpdateTime(new Date());
		if (StringUtils.isNotBlank(increaseResourceVo.getId())) {
			resource.setId(increaseResourceVo.getId());
			this.baseMapper.updateById(resource);
		} else {
			int startNum = getGroupResourceStartNum(increaseResourceVo.getResourceId());
			String id = IdWorker.getId() + "";
			resource.setId(id);
			resource.setName(increaseResourceVo.getName());
			resource.setCateId(increaseResourceVo.getCateId());
			resource.setResourceId(increaseResourceVo.getResourceId());
			resource.setResourceType(4);
			resource.setIsSub(1);
			resource.setSortNum(startNum);
			resource.setCreateBy(PMPHAppUtil.getCurrentUserEnName());
			resource.setCreateTime(new Date());
			this.baseMapper.insert(resource);
		}

	}

	/**
	 * 资源组中的分类
	 * 
	 * @param increaseResourceVo
	 */
	public void addGroupCate(IncreaseResourceVo increaseResourceVo) {
		String pid = increaseResourceVo.getPid();
		QueryWrapper<IncreaseResource> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("pid", pid);
		queryWrapper.orderByDesc("sort_num");
		List<IncreaseResource> listResource = this.baseMapper.selectList(queryWrapper);
		int sortNum = 1;
		if (listResource != null && listResource.size() > 0) {
			sortNum = listResource.get(0).getSortNum() == null ? 1 : listResource.get(0).getSortNum() + 1;
		}

		IncreaseResource resource = new IncreaseResource();
		String id = IdWorker.getId() + "";
		resource.setId(id);
		resource.setName(increaseResourceVo.getName());
		// resource.setBookId(increaseResourceVo.getBookId());
		// resource.setCateId(increaseResourceVo.getCateId());
		resource.setResourceId(increaseResourceVo.getResourceId());
		resource.setPid(increaseResourceVo.getPid());
		resource.setResourceType(4);
		resource.setIsSub(0);
		resource.setSortNum(sortNum);
		resource.setCreateBy(PMPHAppUtil.getCurrentUserEnName());
		resource.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
		resource.setUpdateTime(new Date());
		resource.setCreateTime(new Date());
		this.baseMapper.insert(resource);
	}

	public List<ResourceTreeVo> getResourceGroupTree(String resourceId) {
		List<ResourceTreeVo> list = new ArrayList<>();
		IncreaseResource increaseResource = this.baseMapper.selectById(resourceId);
		String resourceName = increaseResource.getName();
		QueryWrapper<IncreaseResource> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("resource_id", resourceId);
		queryWrapper.orderByAsc("sort_num");
		List<IncreaseResource> listResource = this.baseMapper.selectList(queryWrapper);
		ResourceTreeVo resourceTreeVo = new ResourceTreeVo();
		resourceTreeVo.setId(resourceId);
		resourceTreeVo.setPid(resourceId);
		resourceTreeVo.setType(1);
		resourceTreeVo.setName(resourceName);
		resourceTreeVo.setLabel(resourceName);
		resourceTreeVo.setCateLevel(0);
		resourceTreeVo.setResourceId(resourceId);
		cateTree(listResource, resourceTreeVo);
		list.add(resourceTreeVo);
		return list;
	}

	/**
	 * 获取资源组下的分类选择树，用于将子资源移动到分类下
	 * @param resourceId
	 * @return
	 */
	public List<CategorySelectVo> getResourceSelectTree(String resourceId) {
		List<IncreaseResource> listResource = this.lambdaQuery().eq(IncreaseResource::getResourceId, resourceId)
				.eq(IncreaseResource::getIsSub, 0).list();
		IncreaseResource resoruceGroup = this.getById(resourceId);
		CategorySelectVo vo = new CategorySelectVo();
		vo.setMenuId(resoruceGroup.getId());
		vo.setMenuName(resoruceGroup.getName());
		vo.setOrderNum(1);
		cateSelectTree(listResource, vo);
		List<CategorySelectVo> result = new ArrayList<>();
		result.add(vo);
		return result;
	}

	private static void cateSelectTree(List<IncreaseResource> listCate, CategorySelectVo category) {
		String id = category.getMenuId();
		List<CategorySelectVo> childrenList = listCate.stream().filter(item -> {
			String pid = item.getPid();
			if (id.equals(pid)) {
				return true;
			} else {
				return false;
			}
		}).map(item -> {
			CategorySelectVo vo = new CategorySelectVo();
			vo.setMenuId(item.getId());
			vo.setMenuName(item.getName());
			vo.setOrderNum(item.getSortNum());
			return vo;
		}).sorted(Comparator.comparing(CategorySelectVo::getOrderNum, Comparator.nullsLast(Comparator.naturalOrder())))
				.collect(Collectors.toList());
		category.setChildrenList(childrenList);

		for (int i = 0; i < childrenList.size(); i++) {
			CategorySelectVo cateVo = childrenList.get(i);
			cateSelectTree(listCate, cateVo);
		}
	}

	/**
	 * 向上向下调整排序
	 * 
	 * @param increaseResourceVo
	 * @return
	 */
	public void upOrDownResource(IncreaseResourceVo increaseResourceVo) {
		String id = increaseResourceVo.getId();
		String bookId = increaseResourceVo.getBookId();
		String cateId = increaseResourceVo.getCateId();
		if (StringUtils.isBlank(cateId)) {
			cateId = bookId;
		}
		Integer upDownFlag = increaseResourceVo.getUpDownFlag();// upDownFlag为1向上调位置为2向下调位置

		// 如果该分类下或图书下的资源总数与最大的排序号不一致，则重新排序。现象多发生在历史数据和资源移动到不同目录导致
		List<IncreaseResource> list = getResourceListByCateId(cateId);
		int size = list.size();
		IncreaseResource lastResource = list.get(size - 1);
		int lastNum = lastResource.getSortNum() == null ? 0 : lastResource.getSortNum();
		if (size != lastNum) {
			for (int i = 0; i < list.size(); i++) {
				IncreaseResource temp = list.get(i);
				temp.setSortNum(i + 1);
			}
			this.updateBatchById(list);
		}
		IncreaseResource temp = null;
		IncreaseResource currentData = null;
		for (int i = 0; i < list.size(); i++) {
			currentData = list.get(i);
			if (currentData.getId().equals(id)) {
				if (upDownFlag == 1 && i > 0) {
					temp = list.get(i - 1);
				} else if (upDownFlag == 2 && i < list.size() - 1) {
					temp = list.get(i + 1);
				}
				break;
			}
		}
		if (temp == null) {
			return;
		}
		Integer tempSort = temp.getSortNum();
		Integer currSort = currentData.getSortNum();

		currentData.setSortNum(tempSort);
		temp.setSortNum(currSort);
		temp.setUpdateTime(new Date());
		currentData.setUpdateTime(new Date());
		this.baseMapper.updateById(temp);
		this.baseMapper.updateById(currentData);
	}

	/**
	 * 获取分类下的资源，当资源直属图书时，分类ID为图书
	 * 
	 * @param cateId
	 * @return
	 */
	public List<IncreaseResource> getResourceListByCateId(String cateId) {
		QueryWrapper<IncreaseResource> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("cate_id", cateId);
		queryWrapper.orderByAsc("sort_num");
		return this.baseMapper.selectList(queryWrapper);
	}

	public List<IncreaseResource> getResourceListByCateIdDesc(String cateId) {
		QueryWrapper<IncreaseResource> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("cate_id", cateId);
		queryWrapper.orderByDesc("sort_num");
		return this.baseMapper.selectList(queryWrapper);
	}

	/**
	 * 上下移动资源组的目录，与资源无关
	 * 
	 * @param increaseResourceVo
	 * @return
	 */
	public void upOrDownResourceCate(IncreaseResourceVo increaseResourceVo) {
		String id = increaseResourceVo.getId();
		IncreaseResource increaseResource = this.baseMapper.selectById(id);
		String pid = increaseResource.getPid();
		Integer upDownFlag = increaseResourceVo.getUpDownFlag();// upDownFlag为1向上调位置为2向下调位置

		// 如果id与resourceId相等，则代表资源组本身，不移动
		if (id.equals(increaseResource.getResourceId())) {
			return;
		}

		QueryWrapper<IncreaseResource> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("pid", pid);
		queryWrapper.orderByAsc("sort_num");
		List<IncreaseResource> list = this.baseMapper.selectList(queryWrapper);

		IncreaseResource temp = null;
		IncreaseResource currentData = null;
		for (int i = 0; i < list.size(); i++) {
			currentData = list.get(i);
			if (currentData.getId().equals(id)) {
				if (upDownFlag == 1 && i > 0) {
					temp = list.get(i - 1);
				} else if (upDownFlag == 2 && i < list.size() - 1) {
					temp = list.get(i + 1);
				}
				break;
			}
		}
		if (temp == null) {
			return;
		}
		Integer tempSort = temp.getSortNum();
		Integer currSort = currentData.getSortNum();

		temp.setSortNum(currSort);
		currentData.setSortNum(tempSort);
		temp.setUpdateTime(new Date());
		currentData.setUpdateTime(new Date());
		this.baseMapper.updateById(temp);
		this.baseMapper.updateById(currentData);
	}

	public void batchUploadResource(IncreaseResourceVo increaseResourceVo) {
		String packagePath = increaseResourceVo.getPath();
		File destFile = new File(ApplicationContextUtil.BASE_DOWN_FORDER + packagePath);
		try {
			String unCompress = unCompress(destFile);
			File unDirectFile = new File(unCompress);
			Collection<File> uploadedFiles = FileUtils.listFiles(unDirectFile, null, true);
			for (File temp : uploadedFiles) {
				try {
					relateResource(temp, increaseResourceVo.getBookId(), increaseResourceVo.getCateId());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public List<Map<String,String>> importGroupResourceFile(IncreaseResourceVo increaseResourceVo) {
		List<UploadFileVo> listFile = increaseResourceVo.getFileList();
		String resourceId = increaseResourceVo.getResourceId();
		String cateId = increaseResourceVo.getCateId();
		List<Map<String,String>> uploadMsg = new ArrayList<>();
		for(UploadFileVo fileVo:listFile) {
			Map<String,String> map = new HashMap<>();
			uploadMsg.add(map);
			try {
				String fileUrl = fileVo.getFileUrl();
				String originName = fileVo.getOriginName();
				String fileName = getFileName(originName);
				String suffix = getFileExtName(originName);
				map.put("fileName", originName);
				IncreaseResource resource =null;
				if(".jpg,.jpeg,.png,.bmp".contains(suffix)) {
					resource = getGroupResourceByName(fileName, resourceId, cateId);
					if(resource==null ) {
						map.put("flag", "1");
						continue;
					}
					resource.setPath(fileUrl);
				}else if((".mp3").contains(suffix)){
					resource = getGroupResourceAudioByName(fileName, resourceId, cateId);
					if(resource==null ) {
						map.put("flag", "1");
						continue;
					}
					resource.setAudioPath(fileUrl);
				}
				resource.setUpdateTime(new Date());
				this.updateById(resource);
			} catch (Exception e) {
				map.put("flag", "2");
				e.printStackTrace();
			}
		}
		return uploadMsg;
	}

	public void sendDeleteResourceData(String id, String userName) {
		IncreaseResource increaseResource = new IncreaseResource();
		increaseResource.setId(id);
		Map<String, String> syncDataMap = Maps.newHashMap();
		syncDataMap.put("syncPlatform", "increase");
		syncDataMap.put("userName", userName);
		syncDataMap.put("knowledgeLibId", KnowledgeLib.INCREASE_LIB_ID);
		JSONObject termObject = new JSONObject();
		termObject.put("type", KnowledgeSystem.INCREATE_RESOURCE.value);
		termObject.put("option", "delete");
		termObject.put("data", increaseResource);
		boolean sendFlag2 = RocketMQProducerUtil.sendMessage("increase", "increasebook", increaseResource.getName(),
				JSON.toJSONString(termObject, SerializerFeature.WriteNullListAsEmpty,
						SerializerFeature.WriteNullStringAsEmpty));
		// 记录同步日志
		syncDataMap.put("knowledgeId", increaseResource.getId());
		knowledgeSyncStatusService.insertSync(syncDataMap, sendFlag2);
	}

	public List<IncreaseResource> getResourceByBookId(String bookId) {
		QueryWrapper<IncreaseResource> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("book_id", bookId);
		return this.baseMapper.selectList(queryWrapper);
	}

	private void relateResource(File file, String bookId, String categoryId) throws IOException, InterruptedException {
		String fileAllName = file.getName();
		String fileName = getFileName(fileAllName);
		List<IncreaseResource> listResource = getResourceByName(fileName, bookId, categoryId);
		if (listResource != null && listResource.size() > 0) {
			IncreaseResource resource = listResource.get(0);
			String newFileName = IdWorker.getIdStr() + fileAllName.substring(fileAllName.lastIndexOf("."));
			String newFilePath = "/increaseresource/" + newFileName;
			File newFile = new File(ApplicationContextUtil.BASE_DOWN_FORDER + newFilePath);
			FileUtils.copyFile(file, newFile);
			resource.setPath(newFilePath);
			resource.setImgPath("");
			resourceFileHandler(newFile.getAbsolutePath(), resource, null);
			this.baseMapper.updateById(resource);
		}
	}

	private void resourceFileHandler(String abPath, IncreaseResource resource, IncreaseResource oldResource) {
		String fileSuffix = abPath.substring(abPath.lastIndexOf(".") + 1);
		resource.setResourceType(FfmpegUtil.getResourceType(fileSuffix));
		// 对附件根据类型进行处理
		if (FfmpegUtil.getResourceType(fileSuffix) == 2) {
			// 当为视频类型且未上传封面时，则进行视频截图
			if (StringUtils.isBlank(resource.getImgPath())) {
				try {
					String videoPath = resource.getPath();
					String imgPath = videoPath.substring(0, videoPath.lastIndexOf(".")) + ".png";
					String destImgPath = abPath.substring(0, abPath.lastIndexOf(".")) + ".png";
					FfmpegUtil.getThumb(abPath, destImgPath, 1280, 720, 0, 0, 1);
					resource.setImgPath(imgPath);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			File file = new File(abPath);
			long fileSize = file.length();
			resource.setHdSize(fileSize / 1024 / 1024 + "M");
			resource.setSdSize(fileSize / 1024 / 1024 / 4 + "M");
			// 进行视频压缩处理，原视频均认为是高清资源
			quartzManager.addJob(resource);
		} else if (FfmpegUtil.getResourceType(fileSuffix) == 5) {
			// 当为ppt类型时，需要将ppt转为图片
			PptToImg.convertPptToImg(abPath);
			String imgPptPath = abPath.substring(0, abPath.lastIndexOf("."));
			File file = new File(imgPptPath);
			if (file.exists() && file.isDirectory()) {
				resource.setPptPages(file.list().length);
			}
		} else if (FfmpegUtil.getResourceType(fileSuffix) == 6) {
			// 当为pdf类型时，也将pdf转为图片
			PptToImg.pdfToImg(abPath);
			String imgPptPath = abPath.substring(0, abPath.lastIndexOf("."));
			File file = new File(imgPptPath);
			if (file.exists() && file.isDirectory()) {
				resource.setPptPages(file.list().length);
			}
		}
//			else if (FfmpegUtil.getResourceType(fileSuffix) == 3) {
//				WordUtil.doc2Pdf(abPath);
//			}
	}

	/**
	 * 传进来的为目录（前端传过来图书ID和目录ID,暂时不用这个方法）
	 * 
	 * @param file
	 * @throws IOException
	 */
	private void saveFileToResource(File file, String bookId, String categoryId) throws IOException {

		if (file.exists()) {
			File[] files = file.listFiles();
			if (null != files) {
				for (File temp : files) {
					if (temp.isDirectory()) {
						saveFileToResource(temp, bookId, categoryId);
					} else {
						String fileAllName = temp.getName();
						String fileName = getFileName(fileAllName);
						String fileExtName = getFileExtName(fileAllName);
						List<IncreaseResource> listResource = getResourceByName(fileName, bookId, categoryId);
						if (listResource != null && listResource.size() > 0) {
							IncreaseResource resource = listResource.get(0);
							String newFileName = IdWorker.getIdStr() + fileExtName;
							String newFilePath = ApplicationContextUtil.BASE_DOWN_FORDER + "/increaseresource/"
									+ newFileName;
							File newFile = new File(newFilePath);
							FileUtils.copyFile(temp, newFile);
							resource.setPath(newFilePath);
							this.baseMapper.updateById(resource);
						}
					}
				}
			}
		}
	}

	private String getFileName(String fileAllName) {
		return fileAllName.substring(0, fileAllName.lastIndexOf("."));
	}

	private String getFileExtName(String fileAllName) {
		return fileAllName.substring(fileAllName.lastIndexOf(".") + 1);
	}

	private List<IncreaseResource> getResourceByName(String name, String bookId, String categoryId) {
		QueryWrapper<IncreaseResource> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("book_id", bookId);
		if (StringUtils.isNotBlank(categoryId)) {
			queryWrapper.eq("cate_id", categoryId);
		}
		queryWrapper.eq("file_name", name);
		return this.baseMapper.selectList(queryWrapper);
	}

	private static void cateTree(List<IncreaseResource> listCate, ResourceTreeVo category) {
		String id = category.getId();
		List<ResourceTreeVo> childrenList = listCate.stream().filter(item -> {
			String pid = item.getPid();
			if (id.equals(pid)) {
				return true;
			} else {
				return false;
			}
		}).map(item -> {
			ResourceTreeVo vo = new ResourceTreeVo();
			vo.setId(item.getId());
			vo.setName(item.getName());
			vo.setPid(item.getPid());
			vo.setBookId(item.getBookId());
			vo.setLabel(item.getName());
			vo.setSortNum(item.getSortNum());
			vo.setType(1);
			vo.setResourceId(category.getResourceId());
			return vo;
		}).sorted(Comparator.comparing(ResourceTreeVo::getSortNum, Comparator.nullsLast(Comparator.naturalOrder())))
				.collect(Collectors.toList());
		category.setChildren(childrenList);

		for (int i = 0; i < childrenList.size(); i++) {
			ResourceTreeVo cateVo = childrenList.get(i);
			cateTree(listCate, cateVo);
		}
	}

	private String unCompress(File file) throws Exception {
		String fileName = file.getName();
		int positionIndex = fileName.lastIndexOf(".");
		String extName = fileName.substring(positionIndex + 1).toLowerCase();
		String imgPathName = file.getName().substring(0, file.getName().lastIndexOf("."));
		String destPath = ApplicationContextUtil.BASE_DOWN_FORDER + "/increaseresource/" + imgPathName;
		File outFile = new File(destPath);
		if (!outFile.exists()) {
			outFile.mkdirs();
		}
		if ("zip".equals(extName)) {
			ZipUtil.unzip(file, outFile, Charset.forName("GBK"));
		} else if ("7z".equals(extName)) {
			unCompress7z(file, destPath);
		} else if ("rar".equals(extName)) {
			unCompressRar(file, destPath);
		}
		return destPath;
	}

	private void unCompressRar(File rarFile, String destPath) throws Exception {
		Archive archive = new Archive(new FileInputStream(rarFile));
		FileHeader fileHeader = archive.nextFileHeader();
		while (fileHeader != null) {
			if (fileHeader.isDirectory()) {
				fileHeader = archive.nextFileHeader();
				continue;
			}
			File out = new File(destPath + "/" + fileHeader.getFileName());
			if (!out.exists()) {
				if (!out.getParentFile().exists()) {
					out.getParentFile().mkdirs();
				}
				out.createNewFile();
			}
			FileOutputStream os = new FileOutputStream(out);
			archive.extractFile(fileHeader, os);
			os.close();
			fileHeader = archive.nextFileHeader();
		}
		archive.close();
	}

	public static void unCompress7z(File file, String outFilePath) throws IOException {
		SevenZFile sevenZFile = new SevenZFile(file);
		SevenZArchiveEntry entry = null;
		while ((entry = sevenZFile.getNextEntry()) != null) {
			if (entry.isDirectory()) {
				continue;
			}

			File outputFile = new File(outFilePath + "/" + entry.getName());
			if (!outputFile.exists()) {
				if (!outputFile.getParentFile().exists()) {
					outputFile.getParentFile().mkdirs();
				}
				outputFile.createNewFile();
			}
			byte[] buffer = new byte[1024];
			try (FileOutputStream fos = new FileOutputStream(outputFile)) {
				while (sevenZFile.read(buffer) > 0) {
					fos.write(buffer);
				}
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		sevenZFile.close();
	}

	public int getStartNum(String categoryId) {
		int startSortNum = 1;
		List<IncreaseResource> listResource = getResourceListByCateIdDesc(categoryId);
		if (listResource != null && listResource.size() > 0) {
			IncreaseResource resource = listResource.get(0);
			startSortNum = resource.getSortNum() == null ? 1 : resource.getSortNum() + 1;
		}
		return startSortNum;
	}
	
	private int getGroupResourceStartNum(String resourceId) {
		int startSortNum = 1;
		List<IncreaseResource> listResource = this.lambdaQuery().eq(IncreaseResource::getResourceId, resourceId).last("limit 1").orderByDesc(IncreaseResource::getSortNum).list();
		if (listResource != null && listResource.size() > 0) {
			IncreaseResource resource = listResource.get(0);
			startSortNum = resource.getSortNum() == null ? 1 : resource.getSortNum() + 1;
		}
		return startSortNum;
	}
	
	private IncreaseResource getGroupResourceByName(String name, String resourceId, String cateId) {
		QueryWrapper<IncreaseResource> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("resource_id", resourceId);
		if (StringUtils.isNotBlank(cateId)) {
			queryWrapper.eq("cate_id", cateId);
		}
		queryWrapper.eq("file_name", name);
		List<IncreaseResource> list = this.baseMapper.selectList(queryWrapper);
		if(list!=null && list.size()>0) {
			return list.get(0);
		}
		return null;
	}
	
	private IncreaseResource getGroupResourceAudioByName(String name, String resourceId, String cateId) {
		QueryWrapper<IncreaseResource> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("resource_id", resourceId);
		if (StringUtils.isNotBlank(cateId)) {
			queryWrapper.eq("cate_id", cateId);
		}
		queryWrapper.eq("audio_name", name);
		List<IncreaseResource> list = this.baseMapper.selectList(queryWrapper);
		if(list!=null && list.size()>0) {
			return list.get(0);
		}
		return null;
	}

	public static void main(String[] args) {
		String a = "d:/aa/1500764334030286852.mp4";
		File file = new File(a);

		System.out.println(file.getAbsolutePath());
	}
}
